package org.irri.smta.domain;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name = "REGISTRY")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Registry extends TimestampedIdEntity implements Comparable<Registry> {

	private static final long serialVersionUID = 1L;

	public static final String PATH_SEPARATOR = "/";
	public static final Long REGISTRY_ROOT_ID = 0L;
	public static final String REGISTRY_ROOT_NAME = "ROOT";

	@NotNull
	@Column(name = "NAME", nullable = false)
	@Size(min = 1, max = 100)
	private String name;

	@Column(name = "VALUE", nullable = true)
	@Size(min = 1, max = 2000)
	private String value;

	@ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER)
	@JoinColumn(name = "PARENT_ID", nullable = true)
	private Registry parent;

	@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER)
	private List<Registry> entries;

	public Registry() {
		super();
	}

	public Registry getParent() {
		return parent;
	}

	public void setParent(Registry parent) {
		this.parent = parent;
	}

	public List<Registry> getEntries() {
		return entries;
	}

	public void setEntries(List<Registry> entries) {
		this.entries = entries;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = StringUtils.substring(name.trim(), 0, 100);
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = StringUtils.substring(value.trim(), 0, 2000);
	}

	@Override
	public int compareTo(Registry o) {
		if (o != null) {
			return this.name.compareTo(o.name);
		}
		return 0;
	}

}
